<template>
  <div class="user-article-list">
    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="最新" name="latest" />
      <el-tab-pane label="最热" name="hot" />
    </el-tabs>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <div
      v-else-if="!loading && articleList.length === 0"
      class="empty-container"
    >
      <div class="empty-content">
        <h3>暂无文章</h3>
        <p>
          {{
            isCurrentUser ? "你还没有发布任何文章" : "该用户还没有发布任何文章"
          }}
        </p>
      </div>
    </div>

    <!-- 文章列表 -->
    <div v-else class="articles-list">
      <ArticleCard
        v-for="article in articleList"
        :key="article.id"
        :article="transformArticleData(article)"
        :show-like-count="true"
        :show-collect-count="true"
        :show-interactive-like="false"
        :show-interactive-collect="false"
        class="article-item"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import ArticleCard from "@/components/ArticleCard.vue";
import {
  getUserArticleShowcaseApi,
  type Article,
  type ArticleShowcaseParams
} from "@/api/user-profile";
import type { ArticleTagInfo } from "@/api/article-tag";
import type { ArticleCardItem } from "@/types/user-interactions";

interface Props {
  userId: number | null;
  isCurrentUser?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  isCurrentUser: false
});

// 响应式数据
const loading = ref(false);
const activeTab = ref<"latest" | "hot">("latest");
const latestArticles = ref<Article[]>([]);
const hotArticles = ref<Article[]>([]);

// 计算当前显示的文章列表
const articleList = computed(() => {
  return activeTab.value === "latest"
    ? latestArticles.value
    : hotArticles.value;
});

// 加载文章数据
const loadArticles = async () => {
  if (!props.userId) {
    return;
  }

  try {
    loading.value = true;

    const params: any = {
      latestLimit: 10,
      hotLimit: 10
    };

    const response = await getUserArticleShowcaseApi(props.userId, params);

    if (response.code === 200) {
      const responseData = response.data as any;
      latestArticles.value = responseData.latestArticles || [];
      hotArticles.value = responseData.hotArticles || [];
      console.log(
        `📚 加载用户文章成功 - 最新: ${latestArticles.value.length}, 最热: ${hotArticles.value.length}`
      );
    } else {
      ElMessage.error(response.message || "获取文章列表失败");
    }
  } catch (error) {
    console.error("加载文章列表失败:", error);
    ElMessage.error("获取文章列表失败");
  } finally {
    loading.value = false;
  }
};

// Tab切换处理
const handleTabChange = (tabName: string) => {
  console.log(`📑 切换到 ${tabName === "latest" ? "最新" : "最热"} 文章`);
};

// 转换数据格式以适配ArticleCard组件
const transformArticleData = (article: Article): ArticleCardItem => {
  const articleTags: ArticleTagInfo[] =
    article.tagList && Array.isArray(article.tagList) ? article.tagList : [];

  return {
    articleId: article.id,
    title: article.title,
    summary: article.summary,
    coverImage: article.coverImage,
    authorName: "",
    authorAvatar: "",
    viewCount: article.viewCount || 0,
    likeCount: article.likeCount || 0,
    collectCount: article.collectCount || 0,
    commentCount: article.commentCount || 0,
    publishTime: article.publishTime,
    articleTags: articleTags,
    tags: articleTags
  };
};

// 监听用户ID变化
watch(
  () => props.userId,
  async newUserId => {
    if (newUserId) {
      console.log(`📝 UserArticleList - 用户ID变化: ${newUserId}`);
      await loadArticles();
    }
  },
  { immediate: true }
);

// 组件挂载时加载数据

onMounted(() => {
  console.log(`🔹 UserArticleList 组件挂载 - 用户ID: ${props.userId}`);
  // 移除手动调用，依靠 watch immediate: true 来加载数据
});
</script>

<style scoped lang="scss">
// 响应式适配
@media (width <= 768px) {
  .user-article-list {
    min-height: 300px;
  }

  .empty-container {
    min-height: 300px;

    .empty-content {
      h3 {
        font-size: 16px;
      }

      p {
        font-size: 13px;
      }
    }
  }
}

.user-article-list {
  min-height: 400px;

  :deep(.el-tabs__nav-wrap) {
    margin-bottom: 20px;
  }
}

.loading-container {
  padding: 20px 0;
}

.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;

  .empty-content {
    color: var(--el-text-color-secondary);
    text-align: center;

    h3 {
      margin: 0 0 8px;
      font-size: 18px;
      font-weight: 500;
      color: var(--el-text-color-regular);
    }

    p {
      margin: 0;
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.articles-list {
  .article-item {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 16px;
    }
  }
}
</style>
